/*
 * @Author: dyr
 * @Description: api 接口调用
 * @Date: 2019-06-10 14:52:23
 * @LastEditors: dyr
 * @LastEditTime: 2019-07-07 13:49:55
 */

// import BaseApi from '@/common/request';

import uniStorage from "@/utils/storage";
import {logger} from "@/utils/base_log";
import ApiDefine from "./ApiDefine";

/// <reference path="../defs/ajax.d.ts"/>

//
const API_HOST = "";
//const API_HOST = "http://113.207.112.25:8000";
// const API_HOST = "http://192.168.10.217:15081";

export default class BaseApi {
    onLoginOkWidthToken(token: string) {
        this.tokenObj = token;
        this.saveToken();
        this.isLogin = true;
    }

    isLogin = false;
    userInfo: any = {}
    openId = ""
    phone = ""
    posterId = "";
    nickName = "";


    saveCode() {

    };

    getQueryString(name: string) {
        var result = location.href.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
        if (result == null || result.length < 1) {
            return null;
        }
        return result[1];
    }

    async saveToken() {
        localStorage.setItem('sysuserid', this.sysuserid)
        const d = new Date().getTime();
        var data = {
            token: this.tokenObj,
            time: d,
            openId: this.openId,
            nickname: this.nickName
        };
        uniStorage.setItem("token", JSON.stringify(data));
    }

    async saveAvailableTime(availableTime: number) {
        uniStorage.setItem("availableTime", availableTime.toString());
    }

    async availableTime(): Promise<string> {
        var value: string = await uniStorage.getItem("availableTime");
        return value;
    }

    xrpxTopx(rxCount: number): number {
        var count: any = BaseApi.instance().getSystmeInfo().windowWidth;
        // console.log(count);
        return Number.parseFloat((rxCount * (count / 750)).toFixed(2));
    }

    barHeight = 0;

    showToast(msg: string) {
        uni.showToast({
            title: msg ?? '网络异常',
            icon: "none",
        })
    }

    getBarHeight() {
        this.systemInfo = BaseApi.instance().getSystmeInfo();
        let bottom = this.systemInfo.safeAreaInsets?.bottom ?? (this.systemInfo?.isIphoneXSeries ? 34 : 0)
        this.barHeight = BaseApi.instance().xrpxTopx(110) + bottom;
    }

    systemInfo: any;

    getSystmeInfo() {
        if (this.systemInfo == null) {
            this.systemInfo = uni.getSystemInfoSync()
        }
        return this.systemInfo;
    }

    onGetAccountType(accountType: number) {
        // this.sysConfig = CREATE_SYS_CONFIG(accountType);
    }

    async restoreToken() {
        // if (this.isTokenOk()) return;

        // const d = new Date().getTime();
        // let data: string = await uniStorage.getItem("token");
        // if (!data || data.length == 0) {
        //     logger.info("restoreToken=>Failed: Not in local");
        //     return;
        // }
        // const cc = JSON.parse(data);
        // const dd = cc.time;
        // const dif = d - dd;
        // if (dif > 1000 * 60 * 60 * 24 * 3) {
        //     logger.info("restoreToken=>Failed: expired: " + dif);
        //     return;
        // }
        // // const actype: number = cc.accountType;
        // // this.onGetAccountType(actype);
        // const tk = cc.token;
        // this.tokenObj = tk;
        // this.isLogin = true;
        // this.openId = cc.openId;
        // this.nickName = cc.nickName;
        // console.log(' this.openId====', this.openId)
        // logger.info("restoreToken=>ok:" + data);
    }

    public isTokenOk(): boolean {
        if (this.tokenObj && this.tokenObj.length > 0) {
            return true;
        }
        return false;
    }

    public get token(): string {
        return this.tokenObj;
    }

    public static instance(): BaseApi {
        if (this.instanceObj == null) {
            this.instanceObj = new BaseApi();
            // const x: any = { id: -1, parentId: -1, wechatCode: '' };
        }
        return this.instanceObj;
    }

    private static instanceObj: BaseApi;

    public isLogin: boolean = false;

    private tokenObj: string = "";
    user!: any;

    public logout() {
        let x: any;
        this.isLogin = false;
        this.tokenObj = x;
        this.sysuserid = ''
        this.saveToken();
    }

    sysuserid: any = ''

    private constructor() {
        this.restoreToken();
        //this.sysuserid = localStorage.getItem('sysuserid') ?? ''
        // const c: any = {};
        // this.user = c;
        // this.user.appId = uni.getAccountInfoSync().miniProgram.appId;
    }

    public setCode(code: string) {
        this.user.code = code;
    }

    public resetToken(): void {
        this.tokenObj = "";
    }

    // refreshInWx(url?: string) {
    //   if (!url || url.length === 0) {
    //     url = URL_HOST;
    //   }

    //   url = encodeURI(url);
    //   let uri = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APP_ID}&redirect_uri=${url}&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect`;
    //   window.location.replace(uri);
    // }
    public isInWx(): boolean {
        var ua = window.navigator.userAgent.toLowerCase();
        var isWeixin = ua.indexOf("micromessenger") != -1;
        return isWeixin;
    }


    public async fetch(
        url: string,
        param?: any,
        type: string = "GET",
        header: any = {"content-type": "application/x-www-form-urlencoded"}//{ "content-type": "application/json" }
    ) {
        const t: string = type || "GET";
        url = API_HOST + url;
		console.log('9999',url,param,type,header)
        //header.Base_url =
            //header["X-Token"] = this.tokenObj;
        const err: any = {
            code: 500,
            message: "请求失败",
            result: "",
        };
        const rq: any = {
            url: url,
            data: param,
            header: header,
            method: t,
            timeout: 60000,
        };
        const res: any = await uni.request(rq);
        let r = res[1];
        if (res[0] !== null) {
            err.message = res[0].message;
            r = {data: err};
        }
        logger.info("url=>[" + t + "]" + url, "=>param:", param, "return=>", r);
        return r.data;
    }


    getParamFromUrlQuery(key: string, q: any): string {
        let v = "";
        const kks = Object.keys(q);
        if (!kks || kks.length === 0) return "";
        for (let i = 0; i < kks.length; i++) {
            if (kks[i] === key) {
                const vv = q[key];
                if (vv) {
                    return vv.toString();
                }
            }
        }
        return "";
    }

    boxNo: string = '';

    setBoxNo(boxId: string) {
        this.boxNo = boxId;
    }


    compProp: { [key: string]: any } = {};

    setNexComponentParam(param: { [key: string]: any }) {
        this.compProp = param;
    }

    async initApp(cabinId: number | undefined) {
        const user = BaseApi.instance().user;
        const that = this;
        const cc: any = await uni.login({provider: "weixin"});
        logger.info("init app:", cc);
        const res = cc[1];
        let code = res.code as string;
        logger.info(code);
        BaseApi.instance().setCode(code);
        const appId = BaseApi.instance().user.appId;
        // let bOk: boolean = await ApiUser.initUserInfo(code, appId, cabinId);
        const rr: any = await uni.getUserInfo({provider: "weixin"});
    }

    //0未授权手机号，1授权手机号
    async onAuthPhone(mobile: string) {
        //绑定手机号
        const p = {
            appId: BaseApi.instance().user.appId,
            openid: BaseApi.instance().user.openId,
            mobile: mobile,
        };
        const r = await BaseApi.instance().fetch(
            "/client/user/register",
            p,
            "POST"
        );
        if (r && r.success) {
            console.log(r)
            this.saveAuthPhone(mobile);
            BaseApi.instance().user.mobile = mobile;
            return true;
        }
        return false;
    }

    async saveAuthPhone(authPhone: string) {
        uniStorage.setItem("authPhone", authPhone);
    }

    async getAuthPhone(): Promise<string> {
        var value: string = await uniStorage.getItem("authPhone");
        console.log("getAuthPhone>>>>>" + value);
        return value;
    }

    saveUserInfo(userInfo: any) {
        this.userInfo = userInfo;
    }

    //授权微信信息
    async onAuthResponse(x: any) {
        if (!x || !x.type) return false;
        if (x.type !== "getuserinfo") return false;
        if (!x.detail.userInfo) {
            return false;
        }
        const avater = x.detail.userInfo.avatarUrl;
        const nickName = x.detail.userInfo.nickName;
        const gender = x.detail.userInfo.gender;
        const mobile = x.detail.userInfo.mobile || "";
        if (!gender && !nickName && !avater) {
            return false;
        }
        const p = {
            appId: BaseApi.instance().user.appId,
            openid: BaseApi.instance().user.openId,
            avatarUrl: avater,
            gender: gender,
            nickName: nickName,
            mobile: mobile,
        };
        BaseApi.instance().user.nickName = nickName;
        BaseApi.instance().user.avatarUrl = avater;
        const r = await BaseApi.instance().fetch(
            "/client/user/register",
            p,
            "POST"
        );
        if (r && r.success) {
            console.log(r)
            return true;
        }
        return false;
    }

    getHost(): string {
        return API_HOST;
    }

    static iosOrAndroid(): string {
        let u = navigator.userAgent;
        let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;// android终端
        let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios终端
        let isStr = ''
        if (isAndroid) {
            isStr = 'android'
        }
        if (isiOS) {
            isStr = 'ios'
        }
        return isStr
    }


    testImg = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fyouimg1.c-ctrip.com%2Ftarget%2Ftg%2F035%2F063%2F726%2F3ea4031f045945e1843ae5156749d64c.jpg&refer=http%3A%2F%2Fyouimg1.c-ctrip.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1624455946&t=77c2f9f5b653471afdcc5195676b4798';
}
